package com.lp.chapter001.controller.easyexcel;

import cn.afterturn.easypoi.csv.CsvExportUtil;
import cn.afterturn.easypoi.csv.entity.CsvExportParams;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.lp.chapter001.entity.Student;
import com.lp.chapter001.excel.easyexcel.EasyExcelExcel;
import com.lp.chapter001.excel.easyexcel.EasyExcelImportExcel;
import com.lp.chapter001.excel.easypoi.EasypoiExcel;
import com.lp.chapter001.exception.BizException;
import com.lp.chapter001.mapper.StudentMapper;
import com.lp.chapter001.service.StudentService;
import com.lp.chapter001.service.easyexcel.EasyExcelService;
import com.lp.chapter001.util.ResultData;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.stream.Collectors;

/**
 * EasyExcel-Controller
 * @author LP to 2024/03/30
 */
@RestController
@RequestMapping("/easyExcel")
@Slf4j
@AllArgsConstructor
public class EasyExcelController {

    private final EasyExcelService easyExcelService;
    private final StudentMapper studentMapper;

    /**
     * 下载模板
     * @author LP to 2024/3/30
     */
    @RequestMapping("/download")
    public void easypoiDownload(HttpServletResponse response) {
        try {
            // 如果这里需要后台指定文件名，则可以把文件名定义在请求头里。注意：这里的文件名如果是中文，需要对名称encode
            EasyExcel.write(response.getOutputStream(), EasyExcelExcel.class).sheet().doWrite(Lists.newArrayList());
        } catch (Exception e) {
            throw new BizException("下载easyExcel导入模板失败");
        }
    }

    /**
     * 导入
     * @author LP to 2024/3/30
     */
    @RequestMapping("/import")
    public ResultData<?> easyExcelImport(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BizException("导入文件为空");
        }
        easyExcelService.easyExcelImport(file);
        return ResultData.success();
    }

    /**
     * 导出
     * @author LP to 2024/3/30
     */
    @PostMapping("/export")
    public void easyExcelExport(HttpServletResponse response) {
        try {
            long startTime = System.currentTimeMillis();
            response.setContentType("text/csv");
            Long total = studentMapper.selectCount(null);
            if (total == 0) {
                log.info("查询无数据");
                return;
            }
            ExcelWriter build = EasyExcel.write(response.getOutputStream(), EasyExcelExcel.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
            long page = 1;
            long pageSize = 100_000;
            do {
                Page<Student> studentPage = studentMapper.selectPage(new Page<>(page, pageSize), null);
                build.write(studentPage.getRecords().stream().peek(e -> {
                    EasyExcelExcel excelExcel =  new EasyExcelExcel();
                    excelExcel.setName(e.getName());
                    excelExcel.setStudentNum(e.getStudentNum());
                    excelExcel.setAge(e.getAge());
                    excelExcel.setSex(e.getSex());
                    excelExcel.setBirthday(e.getBirthday());
                }).collect(Collectors.toList()), writeSheet);
                page += 1;
            } while ((page - 1) * pageSize < total);
            build.finish();
            log.info("导出耗时/ms:" + (System.currentTimeMillis() - startTime));
        } catch (Exception e) {
            log.error("easyExcel导出失败,e:{}", e.getMessage(), e);
        }
    }
}
